package ${viewModule.viewPacking}.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Collection;
import javax.transaction.Transactional;
import ${viewModule.viewPacking}.entity.${entityName};
import ${viewModule.viewPacking}.mapper.${entityName}Mapper;
import ${viewModule.viewPacking}.service.I${entityName}Service;
import org.springframework.stereotype.Service;
<#list detailedTable as sub>
import ${viewModule.viewPacking}.mapper.${sub}Mapper;
</#list>
<#list detailedTable as sub>
import ${viewModule.viewPacking}.entity.${sub};
</#list>
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


@Service
public class ${entityName}ServiceImpl extends ServiceImpl<${entityName}Mapper, ${entityName}> implements I${entityName}Service {

    @Autowired
    private ${entityName}Mapper ${entityName?uncap_first}Mapper;
    <#list detailedTable as sub>
    @Autowired
    private ${sub}Mapper ${sub?uncap_first}Mapper;
    </#list>

    @Override
    @Transactional
    public void saveMain(${entityName} ${entityName?uncap_first}, <#list detailedTable as sub>List<${sub}> ${sub?uncap_first}List<#if sub_has_next>,</#if></#list>) {
        ${entityName?uncap_first}Mapper.insert(${entityName?uncap_first});
    <#list detailedTable as sub>
        if(${sub?uncap_first}List != null){
            for(${sub} entity:${sub?uncap_first}List) {
                entity.set${FK}(${entityName?uncap_first}.getId());
                ${sub?uncap_first}Mapper.insert(entity);
            }
        }
    </#list>
    }

    @Override
    @Transactional
    public void updateMain(${entityName} ${entityName?uncap_first},<#list detailedTable as sub>List<${sub}> ${sub?uncap_first}List<#if sub_has_next>,</#if></#list>) {
        ${entityName?uncap_first}Mapper.updateById(${entityName?uncap_first});

        //1.先删除子表数据
    <#list detailedTable as sub>
        ${sub?uncap_first}Mapper.deleteByMainId(${entityName?uncap_first}.getId());
    </#list>

        //2.子表数据重新插入
        <#list detailedTable as sub>
        for(${sub} entity:${sub?uncap_first}List) {
            entity.set${FK}(${entityName?uncap_first}.getId());
            ${sub?uncap_first}Mapper.insert(entity);
        }
        </#list>
    }

    @Override
    @Transactional
    public void delMain(String id) {
    <#list detailedTable as sub>
        ${sub?uncap_first}Mapper.deleteByMainId(id);
    </#list>
        ${entityName?uncap_first}Mapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for(Serializable id:idList) {
        <#list detailedTable as sub>
            ${sub?uncap_first}Mapper.deleteByMainId(id.toString());
        </#list>
            ${entityName?uncap_first}Mapper.deleteById(id);
        }
    }


}
